<?php

namespace App\Models;

use App\MongoModel as Model;
use App\PluginFields;
use App\Services\HelpService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use MongoDB\BSON\UTCDateTime;

class Customer extends Model
{

    protected $fillable = [];
    protected $casts = [
        'wxInfo' => 'object',
    ];

    // 添加默认数据
    const DEFAULT_DATA = [
        '_id' => '',
        'company_id' => '',
        'projects' => [],
        'tags' => [],
        'baseInfo' => [
            'name' => '',
            'mobile' => '',
            'gender' => '',
            'birthday' => '',
            'maritalStatus' => '',
            'work' => '',
            'driverAt' => '',
            'eduLevel' => '',
            'yearIncome' => '',
            'workAddress' => '',
            'homeAddress' => '',
        ],
        'houseInfo' => [
            "_id" => '',
            "authType" => '',
            "address" => [],
            "shhKey" => '',
            "居住情况" => '',
            "同住人" => [],
            "同住人数" => '',
            "最近装修时间" => '',
            "是否贷款" => '',
            "居住时间" => '',
            "租赁形式" => '',
            "租金" => '',
            "租赁时间" => [],
            "租房预算" => '',
        ],
        'socialInfo' => [
            'wechat' => [
                'nickName' => '',
                'remarkName' => '',
                'account' => '',
                'city' => '',
                'headImg' => '',
            ],
            'weibo' => [
                'id' => '',
                'nickName' => '',
            ],
            'shihui' => [
                'id' => '',
                'nickName' => '',
                'regDate' => '',
                'email' => '',
            ],
            'platform' => [
                'system' => '',
                'mediaId' => '',
                'business' => '',
            ]
        ],
        'houseBuy' => [
            '置业考虑' => '',
            '总金额' => '',
            '区域' => [],
            '户型' => '',
            '小区备注' => '',
        ],
        "updated_at" => '',
        "created_at" => '',
    ];

    //年龄
    public function getAgeAttribute() {
        if (isset($this->baseInfo['birthday'])
            && is_numeric($this->baseInfo['birthday'])) {
            $birthday = new \DateTime(date('Y-m-d', $this->baseInfo['birthday']));
            $now = new \DateTime("now");
            $diff = date_diff($birthday, $now);
            return $diff->format('%Y');
        }
        return null;
    }

    public function mergeOne($arr1, $arr2) {
        return array_merge($arr1, $arr2);
    }

    public function merge() {
        $model_data = $this->getAttributes();
        // 此条记录的所有外层key
        $keys = array_keys($model_data);
        // DEFAULT_DATA中外层的key
        $data_keys = array_keys($this::DEFAULT_DATA);
        $social_keys = array_keys($this::DEFAULT_DATA['socialInfo']);
        // DEFAULT_DATA外层中是数组的key
        $arr = [];
        foreach ($data_keys as $k) {
            if (is_array($this::DEFAULT_DATA[$k])) {
                array_push($arr, $k);
            }
        }
        foreach ($arr as $k) {
            if (in_array($k, $keys)) {
                if ($k === 'socialInfo') {
                    $so_keys = array_keys($this[$k]);
                    $temp1 = [];
                    foreach ($so_keys as $so) {
                        $one = $this->mergeOne($this::DEFAULT_DATA[$k][$so], $model_data[$k][$so]);
                        $temp1[$so] = $one;
                    }
                    if (count($social_keys) != count($so_keys)) {
                        foreach ($social_keys as $s) {
                            if (!in_array($s, $so_keys)) {
                                $temp1[$s] = new \stdClass();
                            }
                        }
                    }
                    $this->$k = $temp1;
                    
                } elseif ($k === 'houseInfo') {
                    $house_arr = $this->houseInfo;
                    $temp2 = [];
                    foreach ($house_arr as $h) {
                        $house = array_merge($this::DEFAULT_DATA[$k], $h);
                        $temp2[] = $house;
                    }
                    $this->$k = $temp2;
                } else {
                    $this[$k] = $this->mergeOne($this::DEFAULT_DATA[$k], $model_data[$k]);
                }
            } else {
                if ($k === 'houseInfo' || $k === 'tags' || $k === 'projects') {
                    $this[$k] = [];
                } elseif($k === 'baseInfo' || $k === 'socialInfo' || $k === 'houseBuy') {
                    $this[$k] = new \stdClass();
                } else {
                    $this[$k] = '';
                }
            }
        }
        return $this;
    }

    public function getAllowFields(){
        return array_merge([
            'tags','projects','company_id',
            'baseInfo','houseInfo','houseBuy','socialInfo'
        ]);
    }

    /**
     * 根据联系人和客户资料, 组织微信初始化用客户数据
     * @param array|null $contact 联系人信息数组
     * @return array
     */
    public function contactInfo($contact = null) {
        return [
            'customer_id' => $this->id,
            'name' => array_get($this->baseInfo, 'name', ''),
            'userName' => array_get($this->socialInfo, 'wechat.userName', ''),
            'account' => array_get($this->socialInfo, 'wechat.account', ''),
            'remarkName' => array_get($this->socialInfo, 'wechat.remarkName', ''),
            'nickName' => array_get($this->socialInfo, 'wechat.nickName', ''),
            'mobile' => array_get($this->baseInfo, 'mobile', ''),
            'headImg' => array_get($this->socialInfo, 'wechat.headImg', ''),
            'unreadCount' => 0,
        ];
    }

    public function scopeSearch($query, $inputs) {
        if (HelpService::fromApp()) {
            return $query->where(function ($querys) use ($inputs){
                $user = Auth::User();
                $project = Project::where('users', $user->_id)->first();
                if ($project) {
                    $wx_customers = WxClient::where('project_id', $project->_id)
                        ->get(['contacts'])
                        ->reduce(function($result, $current) {
                            $ids = array_column($current->contacts, 'customer_id');
                            return array_merge($result, $ids);
                        }, []);
                    $querys->whereNotIn('_id', $wx_customers);
                    if(!empty($inputs)){
                        if(!empty($inputs['name'])) {
                            $querys->where([
                                'baseInfo.name' => ['$regex' => (string) $inputs['name']],
                            ]);
                        }
                        if (!empty($inputs['project_id'])) {
                            $querys->whereIn('projects',$inputs['project_id']);
                        }
                    }
                }
            });
        } else {
            if (!empty($inputs)) {
                return $query->where(function ($querys) use ($inputs){
                    if(!empty($inputs['baseInfo.name']) && !empty($inputs['socialInfo.wechat.nickName'])) {
                        $querys->where([
                            '$or' => [
                                ['baseInfo.name' =>
                                    [
                                        '$regex' => $inputs['baseInfo.name'],
                                        '$options' => 'i'
                                    ]
                                ],
                                ['socialInfo.wechat.nickName' =>
                                    [
                                        '$regex' => $inputs['socialInfo.wechat.nickName'],
                                        '$options' => 'i'
                                    ]
                                ]
                            ]
                        ]);
                    }
                    if(!empty($inputs['baseInfo.mobile'])) {
                        $querys->where([
                            'baseInfo.mobile' => ['$regex' => $inputs['baseInfo.mobile']],
                        ]);
                    }
                    if (!empty($inputs['project_id'])) {
                        $querys->whereIn('projects',$inputs['project_id']);
                    }
                    if (!empty($inputs['created_at']) && is_array($inputs['created_at'])) {
                        $start = new UTCDateTime((new Carbon($inputs['created_at'][0]))->timestamp * 1000);
                        $end = new UTCDateTime(
                            ((new Carbon($inputs['created_at'][1]))->timestamp + 24*60*60 - 1) * 1000);
                        $querys->where('created_at', '>=', $start)
                            ->where('created_at', '<=', $end);
                    }
                });
            }
        }
    }

    public function scopeAcceptSearch($query, $project_id, $user_id = null) {
        if (HelpService::fromApp()) {
            return $query->where(function ($querys) {
                $customers = AcceptRecord::where('user_id', Auth::User()->id)
                    ->first();
                $customers = $customers?$customers->customers:[];
                $querys->whereIn('_id', $customers);
            });
        } else {
            $user_id = $user_id ? $user_id : Auth::User()->_id;
            $wx_customers = WxClient::where('project_id', $project_id)
                ->get(['contacts'])
                ->reduce(function($result, $current) {
                    $ids = array_column($current->contacts, 'customer_id');
                    return array_merge($result, $ids);
                }, []);
            $acceptRecord = AcceptRecord::where('user_id', $user_id)
                ->first();
            $accept_customers = $acceptRecord?$acceptRecord->customers:[];
            $customer_id = array_diff($wx_customers, $accept_customers);
            $enable_customer = array_filter($customer_id, function ($id) use ($project_id) {
                $accepted = AcceptRecord::where([
                    'project_id' => $project_id,
                    'customers' => $id,
                ])->count();
                if (!$accepted) {
                    return $id;
                }
            });
            $enable_customer = array_merge($enable_customer, $accept_customers);
            return $query->where(function ($querys) use ($enable_customer){
                $querys->whereIn('_id', $enable_customer);
            });
        }
    }

    public function scopeFindByAccount($query, $account) {
        return $query->where('socialInfo.wechat.account', $account);
    }
}
